package test

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"

	"github.com/pkg/errors"
)

type MyCryptor struct {
	key []byte
}

func NewCryptor(key []byte) *MyCryptor {
	return &MyCryptor{key: key}
}

func (d *MyCryptor) Encrypt(orig []byte) (result []byte, err error) {
	return Encrypt(orig, d.key)
}

func (d *MyCryptor) Decrypt(orig []byte) (result []byte, err error) {
	return Decrypt(orig, d.key)
}

func Encrypt(origData, key []byte) (result []byte, err error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key)
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func Decrypt(crypted, key []byte) (result []byte, err error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5Unpadding(origData)
	return origData, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5Unpadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
